<?php

namespace App\Console\Commands\Cruise;

use App\Models\Cruise\CruiseCheckDetailModel;
use App\Models\Cruise\CruiseTemplateModel;
use Illuminate\Console\Command;

class InitCruiseCheckDetailColumn extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cruise:init-cruise-check-detail-column';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '稽核-初始化cruise check detail column';


    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        CruiseCheckDetailModel
            ::query()
            ->with('cruiseOrderRel')
            ->chunkById(100, function ($details) {
                $details->each(function (CruiseCheckDetailModel $checkDetailModel) {

                    if (!$checkDetailModel->cruiseOrderRel) {
                        return;
                    }

                    $taskName = $checkDetailModel->cruiseOrderRel->getTaskName($checkDetailModel->taskId);
                    if (!$taskName) {
                        $taskName = (string)CruiseTemplateModel::query()->where('id', $checkDetailModel->cruiseOrderRel->templateId)->value('name');
                    }

                    $checkDetailModel->templateId = $checkDetailModel->cruiseOrderRel->templateId;
                    $checkDetailModel->taskName   = $taskName;
                    $checkDetailModel->save();

                    $this->info($checkDetailModel->id);
                });
            });
    }
}
